package com.leoman.filter;

import com.leoman.core.Constant;
import com.leoman.utils.BeanUtil;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信授权过滤器
 * Created by 涂奕恒 on 2015/8/4.
 */
public class CustomWeixinInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            WxCpUser wxUser = (WxCpUser) request.getSession().getAttribute(Constant.SESSION_WEIXIN_WXUSER);
            if (null != wxUser) {
                return true;
            }

            String code;
            try {
                code = request.getParameter("code");
            } catch (Exception e) {
                e.printStackTrace();
                String[] codes = request.getParameterValues("code");

                if (null == codes || codes.length == 0) {
                    return false;
                }

                code = codes[codes.length - 1];
            }

            WxCpUser wxCpUser = (WxCpUser) request.getSession().getAttribute(Constant.SESSION_WEIXIN_WXUSER);
            String type = (String) request.getSession().getAttribute("userRequestType");

            if (null == wxCpUser && StringUtils.isNotEmpty(code)) {
                WxCpService wxCpService;

                if (StringUtils.isBlank(type) || type.equals("2")) {
                    wxCpService = (WxCpService) BeanUtil.getBean("wxCpService");
                } else {
                    wxCpService = (WxCpService) BeanUtil.getBean("wxCpService1");
                }

                String[] strings = wxCpService.oauth2getUserInfo(code);

                if (StringUtils.isNotBlank(strings[0])) {
                    WxCpUser wxCpUserNew = wxCpService.userGet(strings[0]);

                    request.getSession().setAttribute(Constant.SESSION_WEIXIN_WXUSER, wxCpUserNew);
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
